<template>
  <div class="upload-container">
    <div class="upload-box">
      <div class="logo">
        <span class="logo-cloud">数据上传</span>
      </div>

      <el-form :model="form" class="upload-form" ref="uploadFormRef">
        <el-form-item label="数据库：" class="form-item-spacing">
          <el-radio-group v-model="form.databaseType" class="radio-group-center">
            <el-radio label="agricultural">中药农业微生物种质资源库</el-radio>
            <el-radio label="fungi">菌物药种质资源库</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="文件上传：" class="form-item-spacing">
          <el-upload
              class="upload-dragger centered-upload"
              drag
              action="/api/upload"
              :limit="1"
              :on-exceed="handleExceed"
              :on-change="handleFileChange"
              :before-remove="beforeRemove"
              :auto-upload="false"
              :file-list="fileList"
          >
            <el-icon class="el-icon--upload">
              <upload-filled />
            </el-icon>
            <div class="el-upload__text">
              将文件拖到此处，或<em>点击上传</em>
            </div>
            <template #tip>
              <div class="el-upload__tip">
                请上传Excel格式文件（每次只能上传一个文件）
              </div>
            </template>
          </el-upload>
        </el-form-item>

        <el-form-item class="form-item-spacing button-group">
          <div class="buttons-container">
            <el-button
                class="reset-btn"
                @click="handleReset"
            >
              重置
            </el-button>
            <el-button
                type="danger"
                class="submit-btn"
                @click="handleSubmit"
                :loading="isSubmitting"
            >
              提交
            </el-button>
          </div>
        </el-form-item>
      </el-form>
    </div>

    <el-dialog
        v-model="resultDialogVisible"
        :title="resultDialogTitle"
        width="30%"
    >
      <span>{{ resultDialogMessage }}</span>
      <template #footer>
        <div style="text-align: center">
          <el-button @click="resultDialogVisible = false">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { UploadFilled } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { UploadFile, UploadFiles, UploadUserFile } from 'element-plus'
import { dataAgriculturalTask, dataFungiTask } from "~/api/dataApi";

const router = useRouter()

const form = reactive({
  databaseType: 'agricultural' // 默认选中中药农业微生物种质资源库
})

const fileList = ref<UploadUserFile[]>([])
const isSubmitting = ref(false)
const resultDialogVisible = ref(false)
const resultDialogTitle = ref('')
const resultDialogMessage = ref('')
const uploadFormRef = ref()

const handleExceed = () => {
  ElMessage.warning('每次只能上传一个文件，请先移除已选择的文件')
}

const beforeRemove = () => {
  return ElMessageBox.confirm('确定移除该文件吗？')
}

const handleFileChange = (file: UploadFile, files: UploadFiles) => {
  // 确保只保留一个文件
  if (files.length > 1) {
    fileList.value = [files[files.length - 1]] // 只保留最新上传的文件
  } else {
    fileList.value = files as UploadUserFile[]
  }

  // 检查文件类型
  const isExcel = file.raw?.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' ||
      file.raw?.type === 'application/vnd.ms-excel'
  if (!isExcel) {
    fileList.value = []
    return false
  }
}

const handleSubmit = async () => {
  try {
    isSubmitting.value = true

    if (fileList.value.length === 0) {
      showResultDialog('错误', '请先选择要上传的文件')
      return
    }

    const file = fileList.value[0].raw
    if (!file) {
      showResultDialog('错误', '文件无效')
      return
    }

    const formData = new FormData()
    formData.append('file', file)

    let response
    if (form.databaseType === 'agricultural') {
      response = await dataAgriculturalTask(formData)
    } else {
      response = await dataFungiTask(formData)
    }

    if (response?.success) {
      showResultDialog('成功', '数据上传成功！')
      fileList.value = [] // 清空文件列表
    } else {
      showResultDialog('错误', response.msg || '数据上传失败，请重试')
    }

  } catch (error) {
    console.error('上传出错:', error)
    showResultDialog('错误', '数据上传失败，请重试')
  } finally {
    isSubmitting.value = false
  }
}

const handleReset = () => {
  fileList.value = []
  form.databaseType = 'agricultural'
  uploadFormRef.value?.resetFields()
}

const showResultDialog = (title: string, message: string) => {
  resultDialogTitle.value = title
  resultDialogMessage.value = message
  resultDialogVisible.value = true
}
</script>

<style scoped>
/* 保持原有的样式不变 */
.upload-container {
  display: flex;
  justify-content: center;
  margin: 0 200px 0px 200px;
  align-items: center;
  min-height: 100vh;
  background-color: #f5f7fa;
}

.upload-box {
  width: 550px;
  padding: 40px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  text-align: center;
}

.logo {
  margin-bottom: 30px;
  font-size: 32px;
  font-weight: bold;
}

.logo-cloud {
  color: #606266;
}

.upload-form {
  margin-top: 10px;
  max-width: 450px;
  margin-left: auto;
  margin-right: auto;
}

.form-item-spacing {
  margin-bottom: 22px;
}

.button-group {
  margin-top: 30px;
}

.buttons-container {
  display: flex;
  justify-content: center;
  gap: 20px;
  width: 100%;
}

.submit-btn {
  width: 150px;
  background-color: #1b9382;
  border: none;
  color: white;
}

.reset-btn {
  width: 150px;
  border: 1px solid #1b9382;
  color: #1b9382;
}

.el-upload__tip {
  margin-top: 10px;
  color: #909399;
  font-size: 14px;
}

:deep(.el-upload-dragger) {
  width: 100%;
  padding: 20px;
}

.radio-group-center {
  display: flex;
  justify-content: center;
  width: 100%;
}

:deep(.el-radio-group .el-radio) {
  margin-right: 20px;
}

:deep(.el-radio-group .el-radio.is-checked .el-radio__inner) {
  background-color: #1b9382;
  border-color: #1b9382;
}

:deep(.el-radio-group .el-radio.is-checked .el-radio__label) {
  color: #1b9382;
  font-weight: bold;
}

:deep(.el-radio-group .el-radio__input.is-checked+.el-radio__label) {
  color: #1b9382;
}

:deep(.el-radio-group .el-radio__inner:hover) {
  border-color: #1b9382;
}

.centered-upload {
  width: 400px;
}

:deep(.el-upload-dragger:hover),
:deep(.el-upload:focus .el-upload-dragger) {
  border-color: #1b9382;
  color: #1b9382;
}

:deep(.el-upload-dragger .el-icon--upload) {
  color: #1b9382;
}

:deep(.el-upload-dragger:hover .el-icon--upload),
:deep(.el-upload:focus .el-upload-dragger .el-icon--upload) {
  color: #1b9382;
}

:deep(.el-form-item) {
  display: flex;
  align-items: center;
  justify-content: center;
}

:deep(.el-form-item__label) {
  font-size: 16px;
  color: #606266;
  padding-right: 20px;
  text-align: right;
  width: 100px;
}

:deep(.el-form-item__content) {
  flex: 1;
  display: flex;
  justify-content: center;
  margin-left: 0 !important;
}


</style>